package com.innovation.chengzhangriji.service;

import android.content.Intent;
import android.os.IBinder;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.TimelineLastServerTime;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.DataResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.event.BaseEvent;
import com.innovation.chengzhangriji.ui.event.BaseTimelineEvent;

import de.greenrobot.event.EventBus;

public class LoadTimelineService extends BaseSyncTimelineService {

    private int mCount;

    private long mCreateTS;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onTimelineStartCommand() {
        mCount = 0;
        LoginInfo login = Config.getLoginInfo(this);
        if (login == null) {
            stopSelf();
            return;
        }
        final int babyId = login.getBabyID();
        TimelineLastServerTime lastServerTime = DatabaseManager.getInstance(this).queryLastServerTime(babyId);
        if (lastServerTime == null) {
            loadSuccess(0, 0, 0);
            stopSelf();
            return;
        }
        mCreateTS = lastServerTime.getCreateTS();
        syncLastData(login, babyId, lastServerTime.getSyncTS(), lastServerTime.getCreateTS(), lastServerTime.getLastNumber());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void syncLastData(final LoginInfo login, final int babyId, final long syncTS, final long createTS, final int remainNumber) {
        final String phone = login.getPhone();
        final String token = login.getToken().getAccessToken();
        Client.requestSyncLastData(this, phone, token, babyId, Config.QUERY_LENGTH, syncTS, createTS, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                // loadStart();
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                DataResponse dataResponse = get(value.toString(), DataResponse.class);
                if (dataResponse == null) {
                    loadSuccess(0, 0, 0);
                    stopSelf();
                    return;
                }

                int updateNumber = dataResponse.getData().length;
                int newRemainNumber = remainNumber - updateNumber;
                long newCreateTS = dataResponse.getCreateTS();
                System.out.println(newCreateTS);

                String uuid = null;

                for (int i = 0; i < updateNumber; i++) {
                    if (dataResponse.getData()[i].getState() == 1) {
                        uuid = dataResponse.getData()[i].getUuid();
                        mCount++;
                    }
                }
                insertOrReplaceLastServerTime(babyId, uuid, syncTS, newCreateTS, newRemainNumber);
                if (updateNumber > 0) {
                    insertOrReplaceInTxTimeline(babyId, dataResponse);
                    if (newRemainNumber > 0 && mCount < Config.QUERY_LENGTH) {
                        syncLastData(login, babyId, syncTS, newCreateTS, newRemainNumber);
                    } else if (newRemainNumber > 0 && mCount >= Config.QUERY_LENGTH) {
                        loadSuccess(updateNumber, newRemainNumber, mCreateTS);
                        stopSelf();
                    } else {
                        loadSuccess(updateNumber, 0, mCreateTS);
                        stopSelf();
                    }
                } else {
                    loadSuccess(0, 0, 0);
                    stopSelf();
                }
            }

            @Override
            public void onChZhRJFailure(String value) {
                loadFailure(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                loadTokenFailure(value);
                stopSelf();
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                loadFailure(getString(R.string.tip_network_unavailable));
            }
        });
    }

//    private void loadStart() {
//        Intent intent = new Intent();
//        intent.setAction(Config.ACTION_LOAD_TIMELINE_START);
//        sendBroadcast(intent);
//    }

    private void loadSuccess(int updateNumber, int remainNumber, long createTS) {
//        Intent intent = new Intent();
//        intent.setAction(Config.ACTION_LOAD_TIMELINE_SUCCESS);
//        intent.putExtra(Config.ACTION_EXTERNAL_UPDATE_NUMBER, updateNumber);
//        intent.putExtra(Config.ACTION_EXTERNAL_REMAIN_NUMBER, remainNumber);
//        intent.putExtra(Config.ACTION_EXTERNAL_CREATE_TS, createTS);
//        sendBroadcast(intent);

        BaseTimelineEvent event = new BaseTimelineEvent(remainNumber, 0, updateNumber);
        event.setType(BaseEvent.TYPE_TIMELINE_LOAD_MORE);
        event.setState(BaseEvent.STATE_SUCCESS);
        event.setCreateTs(createTS);
        EventBus.getDefault().post(event);
    }

    private void loadFailure(String value) {
//        Intent intent = new Intent();
//        intent.setAction(Config.ACTION_LOAD_TIMELINE_FAILURE);
//        intent.putExtra(Config.ACTION_EXTERNAL_MESSAGE, value);
//        sendBroadcast(intent);

        BaseTimelineEvent event = new BaseTimelineEvent(0, 0, 0);
        event.setType(BaseEvent.TYPE_TIMELINE_LOAD_MORE);
        event.setState(BaseEvent.STATE_FAILURE);
        event.setMessage(value);
        EventBus.getDefault().post(event);
        stopSelf();
    }

    private void loadTokenFailure(String value) {
//        Intent intent = new Intent();
//        intent.setAction(Config.ACTION_LOAD_TIMELINE_TOKEN_FAILURE);
//        intent.putExtra(Config.ACTION_EXTERNAL_MESSAGE, value);
//        sendBroadcast(intent);

        BaseTimelineEvent event = new BaseTimelineEvent(0, 0, 0);
        event.setMessage(value);
        event.setType(BaseEvent.TYPE_TIMELINE_LOAD_MORE);
        event.setState(BaseEvent.STATE_TOKEN_ERROR);
        EventBus.getDefault().post(event);
    }
}
